package com.soo.hoo.admin.api;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.soo.hoo.admin.model.dto.FileDTO;
import com.soo.hoo.admin.model.entity.SysBookReceiving;
import com.soo.hoo.admin.model.entity.SysBookResource;
import com.soo.hoo.admin.service.BookReceivingService;
import com.soo.hoo.admin.service.BookResourceService;
import com.soo.hoo.admin.service.FileService;
import com.soo.hoo.core.annotation.OperateLog;
import com.soo.hoo.core.enums.BusinessTypeEnum;
import com.soo.hoo.core.exception.GlobalException;
import com.soo.hoo.core.model.Page;
import com.soo.hoo.core.model.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Optional;

/**
 * <p>
 * 收礼管理
 * </p>
 *
 * @author 杨燚
 * @since 2024/4/29
 */
@Tag(name = "收礼管理")
@RequestMapping("/receiving/")
@RestController
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class ReceivingController {


    private final BookReceivingService receivingService;
    private final BookResourceService resourceService;

    private final FileService fileService;


    @PostMapping("create")
    @Operation(summary = "")
    @OperateLog(title = "录入收礼记录", businessType = BusinessTypeEnum.CREATE)
    public Result<Void> create(@RequestBody @Valid SysBookReceiving receiving) {
        receiving.setReciprocated(false);
        receivingService.save(receiving);
        return Result.success();
    }

    @Operation(summary = "收礼记录分页")
    @PostMapping("page")
    @OperateLog(title = "分页查询收礼记录", businessType = BusinessTypeEnum.QUERY)
    public Result<Page<SysBookReceiving>> page(@RequestBody @Valid Page<SysBookReceiving> param) {
        Page<SysBookReceiving> page = receivingService.page(param);
        return Result.success(page);
    }

    @PostMapping("update")
    @Operation(summary = "修改收礼记录")
    @OperateLog(title = "修改收礼记录", businessType = BusinessTypeEnum.UPDATE)
    public Result<Void> update(@RequestBody @Valid SysBookReceiving receiving) {
        Long id = Optional.of(receiving.getId()).orElseThrow(
                () -> new GlobalException("修改失败，未找到收礼记录，请联系管理员")
        );
        SysBookReceiving rec = receivingService.getById(id);
        if (rec == null) {
            throw new GlobalException("修改失败，未找到收礼记录，请联系管理员");
        }
        receiving.setReciprocated(rec.getReciprocated());
        receivingService.updateById(receiving);
        return Result.success();
    }

    @DeleteMapping("delete")
    @Operation(summary = "删除收礼记录")
    @OperateLog(title = "删除收礼记录", businessType = BusinessTypeEnum.DELETE)
    public Result<Void> delete(@RequestParam Long id) {
        receivingService.removeById(id);
        return Result.success();
    }

    @GetMapping("receiveAmount")
    @Operation(summary = "获取收礼总金额")
    @OperateLog(title = "获取收礼总金额", businessType = BusinessTypeEnum.QUERY)
    public Result<Integer> getReceiveAmount(@RequestParam Long bookId) {
        List<SysBookReceiving> list = receivingService.list(
                new LambdaQueryWrapper<SysBookReceiving>()
                        .eq(SysBookReceiving::getBookId, bookId)
        );
        return Result.success(
                list.stream().mapToInt(SysBookReceiving::getAmount).sum()
        );
    }

    @PostMapping("template")
    @Operation(summary = "导出模板")
    @OperateLog(title = "导出模板", businessType = BusinessTypeEnum.EXPORT)
    public Result<Void> exportTemplate(HttpServletRequest request, HttpServletResponse response) {
        receivingService.exportTemplate(request, response);
        return Result.success();
    }


    @PostMapping("import")
    @Operation(summary = "导入收礼记录")
    @OperateLog(title = "导入收礼记录", businessType = BusinessTypeEnum.IMPORT)
    public Result<Void> importReceiving(@RequestParam Long booId, @RequestParam MultipartFile file) {
        receivingService.saveDataFromExcel(booId, file);
        FileDTO uploaded = fileService.upload(file, booId + "");
        resourceService.save(
                SysBookResource.builder().bookId(booId).fileId(uploaded.getId()).build()
        );
        return Result.success();
    }
}
